const { key } = require("../config/default");
const { query } = require("../db/mysql");
const {
  queryUserByUsernameAndPassword,
  queryUserByTel,
  updateCodeByTel,
  queryUserByTelAndTelCode,
  insertDataToUser,
  insertDataToUserByUsernameAndPassword,
} = require("../utils");
const JWT = require("jsonwebtoken");
const router = require("koa-router")();
const oo = {};

router.post("/login", async (ctx) => {
  ctx.verifyParams({
    username: { type: "string", required: true },
    password: { type: "string", required: true },
  });
  //1. 获取用户名和密码
  const { username, password } = ctx.request.body;
  // 2. 查询数据库
  const result = await queryUserByUsernameAndPassword(username, password);
  // 3. 返回结果
  if (result) {
    const userInfo = { ...result };
    ctx.body = {
      code: 200,
      message: "登录成功",
      data: {
        userInfo: userInfo,
        token: JWT.sign(userInfo, key),
      },
    };
  } else {
    ctx.body = {
      code: 400,
      message: "账户密码错误， 请重新登录",
    };
  }
});

router.post("/register", async (ctx) => {
  ctx.verifyParams({
    username: { type: "string", required: true },
    password: { type: "string", required: true },
  });
  //1. 获取用户名和密码
  const { username, password } = ctx.request.body;
  // 2. 查询数据库
  const result = await queryUserByUsernameAndPassword(username, password);
  // 3. 返回结果
  if (result) {
    ctx.body = {
      code: 400,
      message: "该用户名已被注册，请重新输入",
    };
  } else {
    const result = await insertDataToUserByUsernameAndPassword(
      username,
      password
    );
    if (result.affectedRows) {
      ctx.body = {
        code: 200,
        message: "注册成功， 请登录",
      };
    } else {
      ctx.body = {
        code: 400,
        message: "注册失败， 请重新注册",
      };
    }
  }
});

router.post("/login/tel", async (ctx) => {
  ctx.verifyParams({
    tel: { type: "string", required: true },
    telCode: { type: "string", required: true },
  });
  //1. 获取手机号
  const { tel, telCode } = ctx.request.body;
  // 2. 查询数据库
  const result = await queryUserByTelAndTelCode(tel, telCode);
  // 3. 返回结果
  if (result) {
    const userInfo = { ...result };
    ctx.body = {
      code: 200,
      message: "登录成功",
      data: {
        userInfo: userInfo,
        token: JWT.sign(userInfo, key),
      },
    };
  } else {
    if (oo[tel] === telCode) {
      const result = await insertDataToUser(tel, telCode);
      if (result.insertId) {
        const result = await queryUserByTelAndTelCode(tel, telCode);
        const userInfo = { ...result };
        ctx.body = {
          code: 200,
          message: "登录成功（自动注册）",
          data: {
            userInfo: userInfo,
            token: JWT.sign(userInfo, key),
          },
        };
      } else {
        ctx.body = {
          code: 400,
          message: "自动注册失败",
        };
      }
    } else {
      ctx.body = {
        code: 400,
        message: "手机号或验证码不正确， 请重新登录",
      };
    }
  }
});

router.get("/login/code", async (ctx) => {
  ctx.verifyParams({
    tel: { type: "string", required: true },
  });
  const { tel } = ctx.query;
  const result = await queryUserByTel(tel);
  const randomCode = Math.random().toString(36).substr(2, 4);
  if (result) {
    updateCodeByTel(tel, randomCode);
    ctx.body = {
      code: 200,
      message: "获取验证码成功",
      data: randomCode,
    };
  } else {
    oo[tel] = randomCode;
    ctx.body = {
      code: 200,
      message: "获取验证码成功(首次登录)",
      data: randomCode,
    };
  }
});

module.exports = router;
